// 全局认证管理模块
// 全局认证管理模块
var AdminGlobal = (function () {
    var module = {};
    var loginPageUrl = "/admin/login";

    // 重新登录
    module.RestartLogin = function (message) {
        layui.use(['layer'], function () {
            var $ = layui.jquery;
            var layer = layui.layer;

            layer.alert(message || "登录状态已失效，请重新登录", {
                icon: 5,
                title: "提示"
            }, function (index) {

                $.ajax({
                    type: 'POST',
                    url: "/admin/index/logout",
                    data: JSON.stringify({ login_token: GetLoginInfo().login_token }),
                    contentType: 'application/json; charset=UTF-8',
                    dataType: 'json',
                    success: function (res) {
                        if (IsSuccess(res.code)) {
                            DelLoginInfo();
                            layer.close(index);
                            setTimeout(function () {
                                // 统一跳转最顶层页面，避免 iframe 嵌套问题
                                window.top.location.href = loginPageUrl;
                            }, 500);
                        } else {
                            layer.alert("操作失败：" + (res.msg || "未知错误"));
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.msg("操作失败：" + (error || "网络异常"));
                    },
                });

            });
        });
    };

    return module;
})();



// ajax全局设置
layui.use(['layer'], function () {
    var token = GetLoginInfo().login_token;
    var $ = layui.$;
    $.ajaxSetup({
        cache: false,
        crossDomain: true,
        headers: {
            'LAdmin-Access-Token': token,
            'Content-Type': 'application/json;charset=utf-8'
        },
        complete: function(xhr) {
            // 安全检查xhr对象
            var code = 0
            if (xhr && xhr.responseJSON) {
                code = xhr.responseJSON.code ? xhr.responseJSON.code : 0
            }
            switch (code) {
                case 401:
                    AdminGlobal.RestartLogin(xhr.responseJSON.msg);
                    break
                case 0:
                    break
                default:
                    layer.msg("操作失败：" + xhr.responseJSON.msg);
                    break
            }

        },
        error: function(xhr, status, error) {
            console.warn('请求错误:', status, error);
        }
    });
})



// 缓存设置登录信息
function SetLoginInfo(data){
    localStorage.setItem(layui.cache.adminAuthKey, JSON.stringify({
        "login_token": data.access_token ,
        "login_name": data.user_name ,
    }));
}

function DelLoginInfo(){
    localStorage.removeItem(layui.cache.adminAuthKey)
}

// 获取登录信息
function GetLoginInfo() {
    var cacheData = localStorage.getItem(layui.cache.adminAuthKey);
    var data = {
        login_token: "",
        login_name : "",
    };

    // 更严格的判断条件
    if (cacheData && typeof cacheData === 'string' && cacheData.trim() !== "") {
        try {
            var info = JSON.parse(cacheData);
            data.login_token = info.login_token || "";
            data.login_name  = info.login_name || "";
        } catch (e) {
            console.error("解析登录信息失败:", e);
        }
    }

    return data;
}


function IsSuccess(code) {
    return code === 0
}


// 格式化接口数据
function FormatListData (res){
    var result = {
        "code": res.code || 0,
        "msg": res.message || "",
        "count": 0,
        "data": []
    };

    // 安全地提取数据
    if (res.data && typeof res.data === 'object') {
        result.count = res.data.total || 0;
        result.data = Array.isArray(res.data.list) ? res.data.list : [];
    }

    return result;
}


function Post (logInfo, url, data){
    var $ = layui.$;
    $.ajax({
        type       : 'POST',
        url        : url,
        data       : JSON.stringify(data),
        contentType: 'application/json; charset=UTF-8',
        headers    : {
            'LAdmin-Access-Token': logInfo.login_token,
        },
        dataType   : 'json',
        success    : function(res){
            if(IsSuccess(res.code)){
                layer.msg('操作成功');
                parent.layer.close(parent.layer.getFrameIndex(window.name));
                parent.layui.table.reload("currentTableId")
            }else{
                layer.alert("操作失败：" + res.msg);
            }
        },
        error : function(xhr, status, error) {
            layer.msg("操作失败：" + error);
        },
    })
}

function FormatInt(id){
    return  parseInt(id) || 0;
}


// 删除函数
function DeleteDataByIds(ids, deleteApiUrl) {
    var deleteReq = {
        "ids": ids,
    }
    var $     = layui.$;
    var table = layui.table;
    layer.confirm('确认删除该数据？', {
        btn: ['确定', '关闭'] // 按钮
    }, function () {
        $.ajax({
            type: 'POST',
            url: deleteApiUrl,
            data: JSON.stringify(deleteReq),
            contentType: 'application/json; charset=UTF-8',
            dataType: 'json',
            success: function (res) {
                if(IsSuccess(res.code)){
                    layer.msg('操作成功');
                } else {
                    layer.alert("操作失败：" + res.msg);
                }
                table.reload('currentTableId');
            }
        })
    });
}
// 数据详情
function GetDataDetailById(id, detailApiUrl) {
    var detailReq = {
        "id": id,
    };
    var $ = layui.$;
    return $.ajax({
        type: 'POST',
        url: detailApiUrl,
        data: JSON.stringify(detailReq),
        contentType: 'application/json; charset=UTF-8',
        dataType: 'json'
    });
}


function PostRequest(logInfo, url, req) {
    var $ = layui.$;
    return new Promise((resolve, reject) => {
        $.ajax({
            type: 'POST',
            url: url,
            data: JSON.stringify(req),
            contentType: 'application/json; charset=UTF-8',
            headers: {
                'LAdmin-Access-Token': logInfo.login_token,
            },
            dataType: 'json',
            success: function(res) {
                if (!IsSuccess(res.code)) {
                    layer.alert("操作失败：" + res.msg);
                    reject(res.msg);
                    return;
                }
                resolve(res.data);
            },
            error: function(xhr, status, error) {
                layer.msg("操作失败：" + error);
                reject(error);
            }
        });
    });
}

async function ApiPost(logInfo, url , req) {
    return await PostRequest(logInfo, url, req);
}
